# 策略： 连续5比Tick上涨买入，连续5比Tick下跌卖出
from vnctptdType661 import *
import globalvar

from PyQt5 import QtWidgets, QtCore

# CTP行情库
from vnctpmd import *
import globalvar
import threading
from threading import Thread
class Strategy(object):


    '''    
    def __init__(self,signal_md_tick):
        self.signal_md_tick = signal_md_tick
        currpath = os.path.abspath(os.path.dirname(__file__))
        self.vnmd = CDLL(currpath + '\\vnctpmd.dll')
    '''

    def __init__(self,type):
        self.type = type
        self.dict_strategyinstrument = {}
        self.dick_tick = {}
        self.list_tick=[]
        self.fee = 0
        self.buyposition = 0
        self.sellposition = 0
        self.amount = 50000
        self.fee = 0

    def InsertOrder(self, InstrumentID , exchangeid, direction, offside, VN_OPT_LimitPrice,  price  , vol):
        if self.type==1:
            #实盘
            globalvar.td.InsertOrder(InstrumentID , exchangeid, direction, offside,VN_OPT_LimitPrice, price, vol)
        elif self.type==2:
            #Python回测
            self.InsertOrder(InstrumentID , exchangeid, direction, offside,VN_OPT_LimitPrice, price, vol)
            pass

    def checkinstrumentID(self,marketdata, strategyname):
        if strategyname in globalvar.dict_strategyinstrument:
            if str(marketdata.InstrumentID, encoding="utf-8") in globalvar.dict_strategyinstrument[strategyname]:
                return 0
            else:
                return 1
        else:
            return 1

class MyStrategy(Strategy, QtCore.QThread):
    def OnTick(self,marketdata,arg, strategyname):
        print(str(marketdata.InstrumentID))
        print(str(arg))
        self.list_tick.append(marketdata.LastPrice)

        directionnum = 0
        for i in range(arg[0]):
            if self.list_tick[i]>self.list_tick[i+1]:
                directionnum = directionnum + 1
            elif self.list_tick[i]<self.list_tick[i+1]:
                directionnum = directionnum - 1

        if directionnum == arg[0]:
            return [1,1]
        else:
            return [-1,-1]


        return [1,1]
        print('T1')
        #print(__name__)  strategyfile000.3tick
        print('T2')
        print(marketdata.InstrumentID)
        print('T21')
        print(str(arg))
        print('T22')
        print(str(marketdata.InstrumentID, encoding="utf-8"))
        print('T23')
        print('合约' + str(marketdata.InstrumentID, encoding="utf-8") + '在策略' + strategyname + '生效')
        print('T3')

        # 检查是否是本策略选中需要交易的合约编码，如果不在则返回，配置在策略文件名称一致的csv文件中，本策略是strategy1.csv，
        if self.checkinstrumentID(marketdata, strategyname):
            return
        print('T4')

        if marketdata.InstrumentID in self.dick_tick:
            pass
        else:
            list_tick = []
            self.dick_tick[marketdata.InstrumentID] = list_tick
            print(str(marketdata.InstrumentID, encoding="utf-8"))
        print('T5')

        self.dick_tick[marketdata.InstrumentID].insert(0, marketdata.LastPrice)
        print('T6')

        if len(self.dick_tick[marketdata.InstrumentID]) > 5:
            print('运行策略(' + strategyname + '.py)： ' + str(marketdata.InstrumentID, encoding="utf-8") + ',' + str(
                marketdata.LastPrice))
            print("比较" + str(marketdata.InstrumentID, encoding="utf-8") + ',' + str(
                self.dick_tick[marketdata.InstrumentID][0]) + ',' +
                  str(self.dick_tick[marketdata.InstrumentID][1]) + ',' + str(self.dick_tick[marketdata.InstrumentID][2]))
            if self.dick_tick[marketdata.InstrumentID][4] > 1e-7 and self.dick_tick[marketdata.InstrumentID][0] > \
                    self.dick_tick[marketdata.InstrumentID][1] and self.dick_tick[marketdata.InstrumentID][1] > \
                    self.dick_tick[marketdata.InstrumentID][2] and self.dick_tick[marketdata.InstrumentID][2] > \
                    self.dick_tick[marketdata.InstrumentID][3] and self.dick_tick[marketdata.InstrumentID][3] > \
                    self.dick_tick[marketdata.InstrumentID][4]:
                print("买入" + str(marketdata.InstrumentID, encoding="utf-8"))
                # 策略池功能完善中
                # 用限价单 VN_OPT_LimitPrice 方式报单 。通常用涨停价限价单模拟市价，因为市价指令不支持所有的交易所
                exchangeid = globalvar.dict_exchange[str(marketdata.InstrumentID, encoding="utf-8")].split(',')[0]

                result = globalvar.td.InsertOrder(str(marketdata.InstrumentID, encoding="utf-8"), exchangeid, '0', '1',
                                                  VN_OPT_LimitPrice, marketdata.LastPrice + 10, 1)
                result = result + globalvar.td.InsertOrder(str(marketdata.InstrumentID, encoding="utf-8"), exchangeid,
                                                           '0', '0', VN_OPT_LimitPrice, marketdata.LastPrice + 10, 1)
                if result == 0:
                    print('报单成功')
                else:
                    print('报单失败')

            elif self.dick_tick[marketdata.InstrumentID][4] > 1e-7 and self.dick_tick[marketdata.InstrumentID][0] < \
                    self.dick_tick[marketdata.InstrumentID][1] and self.dick_tick[marketdata.InstrumentID][1] < \
                    self.dick_tick[marketdata.InstrumentID][2] and self.dick_tick[marketdata.InstrumentID][2] < \
                    self.dick_tick[marketdata.InstrumentID][3] and self.dick_tick[marketdata.InstrumentID][3] < \
                    self.dick_tick[marketdata.InstrumentID][4]:
                print("卖出" + str(marketdata.InstrumentID, encoding="utf-8"))
                # 策略池功能完善中
                # 用限价单 VN_OPT_LimitPrice 方式报单 。通常用涨停价限价单模拟市价，因为市价指令不支持所有的交易所
                exchangeid = globalvar.dict_exchange[str(marketdata.InstrumentID, encoding="utf-8")].split(',')[0]
                result = globalvar.td.InsertOrder(str(marketdata.InstrumentID, encoding="utf-8"), exchangeid, '1', '1',
                                                  VN_OPT_LimitPrice, marketdata.LastPrice - 10, 1)
                result = result + globalvar.td.InsertOrder(str(marketdata.InstrumentID, encoding="utf-8"), exchangeid,
                                                           '1', '0', VN_OPT_LimitPrice, marketdata.LastPrice - 10, 1)
                if result == 0:
                    print('报单成功')
                else:
                    print('报单失败')
